 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.transaction.inputsale;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterItemStock;
import com.ronsicecream.pos.entities.PosMasterPriceOutlet;
import com.ronsicecream.pos.entities.PosMasterStatus;
import com.ronsicecream.pos.entities.PosTransactionInputSale;
import com.ronsicecream.pos.entities.PosTransactionInputSaleDetail;
import com.ronsicecream.pos.entities.PosTransactionItemStock;
import com.ronsicecream.pos.master.item.Item;
import com.ronsicecream.pos.master.status.Status;
import com.ronsicecream.pos.transaction.inputsaledetail.SaleDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class Sale extends Page {
    
    private Field saleId;
    private Field saleNumber;
    private Field saleName;
    private Field saleSubtotal;
    private Field saleDiscountPercent;
    private Field saleDiscountNominal;
    private Field saleTotal;
    private Field saleDate;
    private Field saleTimestamp;
    private Field saleRegionalId;
//    private Field salePosUnitId;
    private Field saleUnitId;
    private Field saleUserId;
    
    public Sale() {
        super();
        
        setTheClass(PosTransactionInputSale.class);
        
        setPageDetail(SaleDetail.class);
        
        
        saleId = new Field();
        saleId.setName("saleId");
        saleId.setCaption("sale id");
        //saleId.setInfo("sale id");
        saleId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        saleId.setInputProperties(" size=\"20\"");
        getFields().add(saleId);
        
        saleNumber = new Field();
        saleNumber.setName("saleNumber");
        saleNumber.setCaption("number");
        saleNumber.setRequired(true);
        saleNumber.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        saleNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(saleNumber);
//        
//        saleName = new Field();
//        saleName.setName("saleName");
//        saleName.setCaption("name");
//        //saleName.setInfo("sale name");
//        saleName.setListProperties(" align=\"left\" width=\"1%\" nowrap");
//        saleName.setInputProperties(" size=\"20\"");
//        getFields().add(saleName);
        
        saleSubtotal = new Field();
        saleSubtotal.setName("saleSubtotal");
        saleSubtotal.setCaption("subtotal");
        //saleSubtotal.setInfo("sale subtotal");
        saleSubtotal.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleSubtotal.setInputProperties(" size=\"20\"");
        getFields().add(saleSubtotal);
        
        saleDiscountPercent = new Field();
        saleDiscountPercent.setName("saleDiscountPercent");
        saleDiscountPercent.setCaption("disc percent");
        saleDiscountPercent.setDefaultValue(0);
        saleDiscountPercent.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleDiscountPercent.setInputProperties(" size=\"20\"");
        getFields().add(saleDiscountPercent);
        
        saleDiscountNominal = new Field();
        saleDiscountNominal.setName("saleDiscountNominal");
        saleDiscountNominal.setCaption("disc nominal");
        saleDiscountNominal.setDefaultValue(0);
        saleDiscountNominal.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleDiscountNominal.setInputProperties(" size=\"20\"");
        getFields().add(saleDiscountNominal);
        
        saleTotal = new Field();
        saleTotal.setName("saleTotal");
        saleTotal.setCaption("total");
        //saleTotal.setInfo("sale total");
        saleTotal.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleTotal.setInputProperties(" size=\"20\"");
        getFields().add(saleTotal);
        
        saleDate = new Field();
        saleDate.setName("saleDate");
        saleDate.setCaption("sale date");
        //saleDate.setInfo("sale date");
        saleDate.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        saleDate.setInputProperties(" size=\"8\"");
        saleDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(saleDate);
        
        saleTimestamp = new Field();
        saleTimestamp.setName("saleTimestamp");
        saleTimestamp.setCaption("timestamp");
        //saleTimestamp.setInfo("sale timestamp");
        saleTimestamp.setListProperties(" align=\"center\" ");
        saleTimestamp.setInputProperties(" size=\"12\"");
        //saleTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(saleTimestamp);
        
        saleRegionalId = new Field();
        saleRegionalId.setName("saleRegionalId");
        saleRegionalId.setCaption("regional");
        saleRegionalId.setRequired(true);
        saleRegionalId.setListProperties(" align=\"left\" width=\"20%\" nowrap");
        saleRegionalId.setInputProperties(" size=\"20\"");
        getFields().add(saleRegionalId);
        
        saleUnitId = new Field();
        saleUnitId.setName("saleUnitId");
        saleUnitId.setCaption("unit");
        //saleUnitId.setInfo("pos master regional");
        saleUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleUnitId.setInputProperties(" size=\"20\"");
        getFields().add(saleUnitId);
        
        saleUserId = new Field();
        saleUserId.setName("saleUserId");
        saleUserId.setCaption("user");
        //saleUserId.setInfo("pos master regional");
        saleUserId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        saleUserId.setInputProperties(" size=\"20\"");
        getFields().add(saleUserId);

//        salePosUnitId = new Field();
//        salePosUnitId.setName("saleOutletId");
//        salePosUnitId.setCaption("outlet");
//        salePosUnitId.setRequired(true);
//        salePosUnitId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
//        salePosUnitId.setInputProperties(" size=\"20\"");
//        getFields().add(salePosUnitId);

        
        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_VIEW);
        
        fillFields();
        
        getFieldsAdd().clear();
        getFieldsAdd().add(saleDate);
        getFieldsAdd().add(saleNumber);
//        getFieldsAdd().add(salePosUnitId);
        getFieldsAdd().add(saleRegionalId);
        getFieldsAdd().add(saleDiscountPercent);
        getFieldsAdd().add(saleDiscountNominal);
        
        getFieldsEdit().clear();
        getFieldsEdit().add(saleNumber);
        getFieldsEdit().add(saleDate);
//        getFieldsEdit().add(saleOutletId);
        getFieldsEdit().add(saleRegionalId);
        getFieldsEdit().add(saleDiscountPercent);
        getFieldsEdit().add(saleDiscountNominal);
        
        getFieldsList().clear();
        getFieldsList().add(saleNumber);
        getFieldsList().add(saleDate);
//        getFieldsList().add(saleOutletId);
        getFieldsList().add(saleRegionalId);
        getFieldsList().add(saleSubtotal);
        getFieldsList().add(saleDiscountPercent);
        getFieldsList().add(saleDiscountNominal);
        getFieldsList().add(saleTotal);
        
        getFieldsView().clear();
        getFieldsView().add(saleNumber);
//        getFieldsView().add(salePosUnitId);
        getFieldsView().add(saleRegionalId);
        getFieldsView().add(saleSubtotal);
        getFieldsView().add(saleDiscountPercent);
        getFieldsView().add(saleDiscountNominal);
        getFieldsView().add(saleTotal);
        getFieldsView().add(saleTimestamp);
        
        setController(new SaleController(this));
         setExportList(getClass().getResourceAsStream("SsaleList.jasper"));
        setExport(getClass().getResourceAsStream("Sale.jasper"));
    }
    
    @Override
    public void beforeList() {
        if (!getCurrentUnit().getUnitId().equals(1)) {
            getController().setCondition("t.saleUnitId.unitId=" + getCurrentUnit().getUnitId());
        } else {
            return;
        }
        
    }
    
    @Override
    public void loadDetail(List datas, String id) {
        try {
            EntityManager em = getEntityManager();
            List<PosTransactionInputSaleDetail> request = em.createQuery("SELECT t FROM PosTransactionInputSaleDetail t WHERE t.saleDetailSaleId.saleId='" + id + "'").setHint(Persistence.REFRESH_HINT, true).getResultList();
            datas.clear();
            for (PosTransactionInputSaleDetail saleDetail : request) {
                PosTransactionInputSale sale = new PosTransactionInputSale();
                sale.setSaleDiscountNominal(saleDetail.getSaleDetailDiscountNominal());
                sale.setSaleDiscountPercent(saleDetail.getSaleDetailDiscountPercent());
                datas.add(sale);
            }
        } catch (Exception e) {
            Logger.getInstance().log(e);
        }
    }
    
    @Override
    public void beforeAdd() {
        saleNumber.setDefaultValue(generate());
    }

//    @Override
//    public void beforeList() {
//        getController().setCondition("t.saleUnitId.unitId=" + getCurrentUnit().getUnitId());
//    }
    class SaleController extends Controller {
        
        public SaleController(Page page) {
            super(page);
            setOrder(saleTimestamp);
            setOrderType("DESC");
        }
        
        @Override
        public void beforeInsert(Object data, List list) {
            PosTransactionInputSale sale = (PosTransactionInputSale) data;
            sale.setSaleNumber(generate());
            sale.setSaleUserId(getCurrentUser());
//            sale.setSaleSalesId(getCurrentUser());
            sale.setSaleUnitId(getCurrentUnit());
            sale.setSaleTimestamp(Utility.getTimestamp());

//            for (int i = list.size() - 1; i > 0; i--) {
//                PosTransactionSaleDetail d1 = (PosTransactionSaleDetail) list.get(i);
//                for (int j = 0; j < i; j++) {
//                    PosTransactionSaleDetail d2 = (PosTransactionSaleDetail) list.get(j);
//                    if (d2.getSaleDetailItemId().equals(d1.getSaleDetailItemId())) {
//                        d2.setSaleDetailQuantity(d2.getSaleDetailQuantity()+d1.getSaleDetailQuantity());
//                        list.remove(i);
//                        break;
//                    }
//                }
//            }

//            BigDecimal subTotal = BigDecimal.ZERO;
//            for (int i = 0; i < list.size(); i++) {
//                PosTransactionInputSaleDetail saleDetail = (PosTransactionInputSaleDetail) list.get(i);
//                subTotal = subTotal.add(saleDetail.getSaleDetailTotal());
//            }
//            BigDecimal total = subTotal;
//            BigDecimal percent = BigDecimal.ZERO;
//            try {
//                percent = subTotal.multiply(sale.getSaleDiscountPercent().divide(new BigDecimal(100)));
//            } catch (Exception e) {
//                Logger.getInstance().log(e);
//            }
//            total = total.subtract(percent);
//            try {
//                total = total.subtract(sale.getSaleDiscountNominal());
//            } catch (Exception e) {
//                Logger.getInstance().log(e);
//            }
//            sale.setSaleSubtotal(subTotal);
//            sale.setSaleTotal(total);
        }
        
        @Override
        public void afterInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionInputSale sale = (PosTransactionInputSale) data;
                BigDecimal total = BigDecimal.ZERO;
                BigDecimal subtotal = BigDecimal.ZERO;
                BigDecimal quantity = BigDecimal.ZERO;
                BigDecimal totalsubtotal = BigDecimal.ZERO;
                for (Object detail : list) {
                    PosTransactionInputSaleDetail saleDetail = (PosTransactionInputSaleDetail) detail;
//                    PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
//                            + " WHERE t.unitUnitTypeId.unitTypeId=4 "
//                            + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId())
//                            //                            + " AND t.unitRegionalId.regionalId="+sale.getSaleRegionalId().getRegionalId())
//                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                    System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
//                    
                    
                    PosMasterPriceOutlet price = (PosMasterPriceOutlet) em.createQuery("SELECT t FROM PosMasterPriceOutlet t"
                            + " WHERE t.pricePosUnitId.unitId=" + getCurrentUnit()
                            + " AND t.priceItemId.itemId=" + saleDetail.getSaleDetailItemId().getItemId())
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    saleDetail.setSaleDetailPrice(price.getPricePrice());

//            PosMasterStockProduct stock = Product.getStock(em, saleDetail.getSaleDetailProductId(), getCurrentUnit(), statusGood, saleDetail.getSaleDetailProductId().getProductTypeId());
                    
//            BigDecimal quantity = new BigDecimal(saleDetail.getSaleDetailQuantity());
                    subtotal = saleDetail.getSaleDetailPrice().multiply(saleDetail.getSaleDetailQuantity());
                    BigDecimal percent = BigDecimal.ZERO;
                    try {
                        percent = subtotal.multiply(saleDetail.getSaleDetailDiscountPercent().divide(new BigDecimal(100)));
                    } catch (Exception e) {
                        Logger.getInstance().log(e);
                    }
                    subtotal = subtotal.subtract(percent);
                    try {
                        subtotal = subtotal.subtract(saleDetail.getSaleDetailDiscountNominal());
                    } catch (Exception e) {
                        Logger.getInstance().log(e);
                    }
                    saleDetail.setSaleDetailTotal(subtotal);
                    
                    quantity = quantity.add(saleDetail.getSaleDetailQuantity());
                    totalsubtotal = totalsubtotal.add(saleDetail.getSaleDetailTotal());
                    total = total.add(saleDetail.getSaleDetailPrice().multiply(saleDetail.getSaleDetailQuantity()));
                    
                    
                    PosMasterItemStock stock = Item.getStockItem(em, saleDetail.getSaleDetailItemId(), getCurrentUnit());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();
                    
                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(saleDetail.getSaleDetailItemId());
                    itemStock.setItemStockUnitId(getCurrentUnit());
//                    itemStock.setItemStockStatusId(statusGood);
                    itemStock.setItemStockType("7");
//                    itemStock.setItemStockRegionalId(sale.getSaleRegionalId());
//                    itemStock.setItemStockPosUnitId(posunit);
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockValue(saleDetail.getSaleDetailQuantity());
                    itemStock.setItemStockCurrent(stock.getItemStockValue().subtract(itemStock.getItemStockValue()));
                    itemStock.setItemStockUserId(getCurrentUser());
//                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    System.out.println(itemStock.getItemStockId() + "<<=========dedy=");
                    em.persist(itemStock);
                    stock.setItemStockValue(itemStock.getItemStockCurrent());
                    stock.setItemStockTimestamp(Utility.getTimestamp());
                }
                sale.setSaleSubtotal(total);
                sale.setSaleQuantity(quantity);
                sale.setSaleTotal(subtotal);
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println("Errrrrrr :" + e);
            }
        }
    }
    
    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionInputSale rec = (PosTransactionInputSale) getEntityManager().createQuery("SELECT t FROM PosTransactionInputSale t "
                    + "WHERE t.saleNumber LIKE '%/" + unitCode + "/Rons/SALE/%/" + year + "' "
                    + "ORDER BY t.saleTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(rec.getSaleNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/SALE/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/SALE/" + month + "/" + year;
    }
    
    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Sale"));
    }
    
    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
